package com.example.community.controller;

import com.example.community.entity.DiscussPost;
import com.example.community.entity.Page;
import com.example.community.entity.User;
import com.example.community.service.DiscussPostService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;

import com.example.community.util.CommunityConstant;
import com.example.community.util.CommunityUitl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    /**
     *  分页查询 帖子列表
     * @param model
     * @param page 从页面出来的分页信息，
     * @return
     */
    @RequestMapping(path = "/index", method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page,@RequestParam(name ="orderMode", defaultValue = "0") int orderMode){
        // userId == 0 所有帖子的信息
        page.setRows(discussPostService.findDiscussPostRows(0));
        page.setPath("index?orderMode=" + orderMode);

        List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit(), orderMode);
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if(list != null){
            for(DiscussPost post : list){
                // 列表信息为多表查询的结果,所以需要用户id来查询出用户信息
                Map<String, Object> map = new HashMap<>();
                // 帖子
                map.put("post", post);
                // 发帖子人
                User user = userService.findUserById(post.getUserId());
                map.put("user", user);

                // 点赞数
                long likeCount = likeService.findEntityLIkeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount",likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("orderMode", orderMode);

        return "index";
    }

    // 拒绝访问的提示页面- 没有权限
    @RequestMapping(path = "/denied", method = {RequestMethod.GET})
    public String getDeniedPage() {
        return "error/404";
    }
}
